#include <iostream>
#include <vector>

using namespace std;
class Solution {
public:
    int findroot(const vector<int>& ufs, int x)
    {
        int root = x;
        while (ufs[root] >= 0)
            root = ufs[root];
        return root;
    }

    int findCircleNum(vector<vector<int>>& isConnected) {
        vector<int> ufs(isConnected.size(), -1);
        for (int i = 0; i < isConnected.size(); ++i)
        {
            for (int j = 0; j < isConnected[i].size(); ++j)
            {
                if (isConnected[i][j] == 1)
                {
                    int root1 = findroot(ufs, i);
                    int root2 = findroot(ufs, j);
                    if (root1 != root2)
                    {
                        ufs[root1] += ufs[root2];
                        ufs[root2] = root1;
                    }
                }
            }
        }
        int ret = 0;
        for (auto e : ufs)
        {
            if (e < 0)
                ret++;
        }
        return ret;
    }
};